package com.zwl.smartplatform.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
public class BeanConfig {

    @Bean
    public DataSource source(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("010429");
        druidDataSource.setUrl("jdbc:mysql:///smartplatfrom?useUnicode=true&characterEncoding=utf8&useSSL=false");
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        return druidDataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource source){

        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(source);//设置数据库的连接
        org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);//开启驼峰命名 也就是表中的a_b列会被封装到对象中的aB属性
        sqlSessionFactoryBean.setConfiguration(configuration);
        PageInterceptor pageInterceptor = new PageInterceptor();//分页的插件
        sqlSessionFactoryBean.setPlugins(pageInterceptor);//设置分页的插件
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer configurer=new MapperScannerConfigurer();
        configurer.setBasePackage("com.zwl.smartplatform.mapper");
        return configurer;
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource source){
        DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(source);
        return dataSourceTransactionManager;
    }
}
